package com.yunyao.framework.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.yunyao.client.request.PageRequest;
import com.yunyao.client.request.UserRequest;
import com.yunyao.client.response.UserResponse;
import com.yunyao.client.service.MdmClientService;
import com.yunyao.common.constant.enums.DataDeletedStatus;
import com.yunyao.common.constant.enums.DateFormatPattern;
import com.yunyao.common.core.BaseContext;
import com.yunyao.common.dto.UserDto;
import com.yunyao.common.dto.UserLoginDto;
import com.yunyao.common.sign.Md5Util;
import com.yunyao.common.web.util.ConvertUtil;
import com.yunyao.common.web.util.PageResult;
import com.yunyao.common.web.util.YResult;
import com.yunyao.dao.model.BamuProjectMember;
import com.yunyao.dao.model.BamuSaleContract;
import com.yunyao.dao.model.SysRole;
import com.yunyao.dao.model.User;
import com.yunyao.dao.service.bamu.IBamuProjectMemberService;
import com.yunyao.dao.service.bamu.IBamuSaleContractService;
import com.yunyao.dao.service.system.ISysRoleService;
import com.yunyao.dao.service.system.IUserService;
import com.yunyao.framework.dto.user.UserDeleteDto;
import com.yunyao.framework.dto.user.UserSaveDto;
import com.yunyao.framework.service.UserService;
import com.yunyao.framework.vo.user.UserDeptVO;
import com.yunyao.framework.vo.user.UserInfoVO;
import com.yunyao.framework.vo.user.UserVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * @author xingjishuai
 * @date 2024-07-16
 */
@Slf4j
@Service("userService")
public class UserServiceImpl implements UserService {
    @Autowired
    private MdmClientService mdmClientService;

    @Autowired
    private IUserService iBamuUserService;
    @Autowired
    private ISysRoleService iBamuSysRoleService;
    @Autowired
    private IBamuProjectMemberService iBamuProjectMemberService;
    @Autowired
    private IBamuSaleContractService iBamuSaleContractService;
    @Value("${default.user.password}")
    private String defaultUserPassword;
    @Value("${default.tenant.id}")
    private String defaultTenantId;

    @Override
    public YResult<PageResult<UserDeptVO>> getDeptList(UserDto userDto) {
        Long pageIndex = userDto.getPageIndex();
        Long pageSize = userDto.getPageSize();
        String account = userDto.getAccount();
        String deptId = userDto.getDeptId();
        String realName = userDto.getRealName();
        IPage<User> userPage = iBamuUserService.getDeptList(pageIndex, pageSize, deptId, realName
                , account);

        // 处理查询结果
        if (CollectionUtils.isEmpty(userPage.getRecords())) {
            return YResult.success(new PageResult<>());
        }

        // 转换为VO对象列表
        List<UserDeptVO> userVoList = treeDaoToVoList(userPage.getRecords());

        // 返回分页结果
        return YResult.success(new PageResult<>(userVoList, userPage.getCurrent(), userPage.getSize(), userPage.getPages(), userPage.getTotal()));
    }

    @Override
    public YResult<PageResult<UserDeptVO>> pageList(UserDto userDto) {
        return getDeptList(userDto);
    }

    @Override
    public YResult<UserInfoVO> getByIdInfo(UserDto userDto) {
        try {
            String id = userDto.getId();
            User user = iBamuUserService.getByIdNoDel(id);
            if (Objects.isNull(user)) {
                return YResult.error("用户不存在");
            }
            UserInfoVO userInfoVO = new UserInfoVO();
            BeanUtils.copyProperties(user, userInfoVO);
            userInfoVO.setBirthday(ConvertUtil.getFormatDateGMT(user.getBirthday(),
                    DateFormatPattern.YEAR_MONTH_DAY.getPattern()));
            userInfoVO.setExpireTime(ConvertUtil.getFormatDateGMT(user.getExpireTime(),
                    DateFormatPattern.YEAR_MONTH_DAY_HOUR_MINUTE_SECOND.getPattern()));
            return YResult.success(userInfoVO);
        } catch (Exception ex) {
            log.error("查询用户信息失败", ex);
            return YResult.error(ex.getMessage());
        }
    }

    @Override
    public YResult<String> deleteById(UserDeleteDto userDeleteDto) {
        try {
            if (StringUtils.isBlank(userDeleteDto.getId())) {
                return YResult.error("用户ID不能为空");
            }
            User user = iBamuUserService.getByIdNoDel(userDeleteDto.getId());
            if (Objects.isNull(user)) {
                return YResult.error("用户不存在");
            }
            user.setIsDeleted(DataDeletedStatus.YES.getType());
            iBamuUserService.updateById(user);
            return YResult.success(user.getId());
        } catch (Exception ex) {
            log.error("删除用户信息失败", ex);
            return YResult.error(ex.getMessage());
        }

    }

    @Override
    public YResult<String> save(UserSaveDto userSaveDto) {
        try {
            User user = new User();
            String newPassword = userSaveDto.getNewPassword();
            String confirmPassword = userSaveDto.getConfirmPassword();
            if (StringUtils.isNotBlank(newPassword) && StringUtils.isNotBlank(confirmPassword)) {
                if (!StringUtils.equals(newPassword, confirmPassword)){
                    return YResult.error("两次密码不一致");
                }
                user.setPassword(Md5Util.getMD5String(newPassword));
            }
            BeanUtils.copyProperties(userSaveDto, user);
            iBamuUserService.saveOrUpdate(user);
            return YResult.success(user.getId());
        } catch (Exception ex) {
            log.error("保存用户信息失败", ex);
            return YResult.error(ex.getMessage());
        }
    }

    @Override
    public YResult<String> passwordReset() {
        String userId = BaseContext.getUserId();
        if (StringUtils.isBlank(userId)) {
            return YResult.error("用户未登录");
        }
        User user = iBamuUserService.getByIdNoDel(userId);
        if (Objects.isNull(user)) {
            return YResult.error("用户不存在");
        }
        user.setPassword(Md5Util.getMD5String(defaultUserPassword));
        iBamuUserService.updateById(user);
        return YResult.success("重置成功");
    }

    @Override
    public YResult<String> syncMdm(UserDto userDto) {
        try {
            syncMdmHandle(userDto);
            return YResult.success("同步成功");
        } catch (Exception ex) {
            log.error("同步用户信息失败", ex);
            return YResult.error(ex.getMessage());
        }
    }

    @Override
    public YResult<String> passwordDefault() {
        return YResult.success(defaultUserPassword);
    }

    @Async
    public void syncMdmHandle(UserDto userDto) {
        String beginDate = userDto.getBeginDate();
        UserRequest userRequest = new UserRequest();
        userRequest.setLastModifyRecordTime(beginDate + "~");
        long pageIndex = 1;
        List<UserResponse> records = new ArrayList<>();
        do {
            PageRequest pageRequest = new PageRequest();
            pageRequest.setPageIndex(pageIndex);
            pageRequest.setPageSize(50L);
            PageResult<UserResponse> responsePageResult =
                    mdmClientService.userPageList(userRequest, pageRequest);
            records = responsePageResult.getRecords();
            if (CollectionUtils.isEmpty(records) || pageIndex > responsePageResult.getTotalPages()) {
                break;
            }
            for (UserResponse userResponse : records) {
                String account = userResponse.getAccount();
                if (StringUtils.isBlank(account)) {
                    continue;
                }
                User user = iBamuUserService.getByAccount(account, defaultTenantId);
                if (Objects.nonNull(user)){
                    continue;
                }
                user = new User();
                user.setAccount(userResponse.getAccount());
                user.setRealName(userResponse.getRealName());
                user.setNickName(userResponse.getRealName());
                user.setPhone(userResponse.getPhone());
                user.setSex(userResponse.getSex());
                user.setTenantId(defaultTenantId);
                user.setRoleId("cloudPurchase");
                user.setPassword(Md5Util.getMD5String(defaultUserPassword));
                user.setSource(10);
                user.setSyncUserId(userResponse.getSyncUserId());
                iBamuUserService.save(user);
            }
            pageIndex++;
        } while (CollectionUtils.isNotEmpty(records));
    }


    private List<UserDeptVO> treeDaoToVoList(List<User> records) {
        List<String> roleIdList = records.stream()
                .filter(x -> StringUtils.isNotBlank(x.getRoleId()))
                .map(x -> x.getRoleId().split(",")[0]).distinct()
                .toList();
        Map<String, SysRole> roleMapByIds = iBamuSysRoleService.getRoleMapByIds(roleIdList);
        return records.stream().map(x -> treeDaoToVo(x, roleMapByIds)).collect(Collectors.toList());
    }

    private UserDeptVO treeDaoToVo(User bamuUser, Map<String, SysRole> roleMapByIds) {
        UserDeptVO userVO = new UserDeptVO();
        BeanUtils.copyProperties(bamuUser, userVO);
        String roleId = bamuUser.getRoleId();
        if (StringUtils.isNotBlank(roleId)) {
            String[] roleIdArr = roleId.split(",");
            if (roleIdArr.length > 0) {
                String roleOne = roleIdArr[0];
                if (StringUtils.equals("-1", roleOne)) {
                    userVO.setRoleName("项目部");
                }
                SysRole role = roleMapByIds.get(roleOne);
                if (null != role) {
                    userVO.setRoleName(role.getRoleName());
                }

            }
        }
        return userVO;
    }


    @Override
    public UserVO checkPassword(UserLoginDto userDto, String md5Password) {

        // 构建查询条件
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<User>()
                .eq(User::getAccount, userDto.getUsername()).eq(User::getPassword, md5Password).eq(User::getIsDeleted, 0).eq(User::getTenantId,"000000");
        try {
            UserVO userVo = new UserVO();
            Optional<User> oneOpt = iBamuUserService.getOneOpt(queryWrapper);
            if (oneOpt.isPresent()) {
                User user = oneOpt.get();
                userVo.setId(user.getId());
                userVo.setAccount(user.getAccount());
                userVo.setRealName(user.getRealName());
                userVo.setRoleIds(user.getRoleId());
                userVo.setDeptId(user.getDeptId());
                userVo.setTenantId(user.getTenantId());
                return userVo;
            }
            return null;
        }catch (Exception e) {
            log.error("查询用户信息失败", e);
            return null;
        }

    }

    @Override
    public UserVO getUserInfo(String userId) {
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<User>()
                .eq(User::getId, userId)
                .eq(User::getIsDeleted, DataDeletedStatus.NO.getType());
        User user = iBamuUserService.getOne(queryWrapper);
        if (Objects.isNull(user)) {
            return null;
        }
        UserVO userVO = new UserVO();
        BeanUtils.copyProperties(user, userVO);
        userVO.setRoleIds(user.getRoleId());
        List<String> roleIdList = List.of(user.getRoleId().split(","));


        List<String> projectIdList = new ArrayList<>();
        List<String> supplierIdList = new ArrayList<>();
        /**
         * 只有用户为供应商一个角色时，才会生效
         */
        userVO.setIsSupplier(false);
        userVO.setIsProject(false);
        if (roleIdList.size() == 1 && roleIdList.contains("supply")) {
            userVO.setIsSupplier(true);
            LambdaQueryWrapper<BamuSaleContract> contractLambdaQueryWrapper = new LambdaQueryWrapper<>();
            contractLambdaQueryWrapper.eq(BamuSaleContract::getSupplierDeptId, user.getDeptId())
                    .eq(BamuSaleContract::getIsDeleted, DataDeletedStatus.NO.getType());
            List<BamuSaleContract> contractList = iBamuSaleContractService.list(contractLambdaQueryWrapper);
            if (CollectionUtils.isNotEmpty(contractList)){
                for (BamuSaleContract bamuSaleContract : contractList) {
                    projectIdList.add(bamuSaleContract.getProjectId());
                    supplierIdList.add(bamuSaleContract.getSupplierDeptId());
                }
            }else {
                // 默认返回一个项目id，表示没有项目，防止判断为空查询出所有项目
                projectIdList.add("-1");
                supplierIdList.add("-1");
            }

            userVO.setSupplierIds(supplierIdList);
        }

        /**
         * 只有用户为项目部一个角色时，才会生效
         */
        if (roleIdList.size() == 1 && roleIdList.contains("project")) {
            userVO.setIsProject(true);
            LambdaQueryWrapper<BamuProjectMember> projectMemberLambdaQueryWrapper = new LambdaQueryWrapper<>();
            projectMemberLambdaQueryWrapper.eq(BamuProjectMember::getUserId, userId)
                    .eq(BamuProjectMember::getIsDeleted, DataDeletedStatus.NO.getType());
            List<BamuProjectMember> projectMemberList = iBamuProjectMemberService.list(projectMemberLambdaQueryWrapper);
            if (CollectionUtils.isNotEmpty(projectMemberList)) {
                for (BamuProjectMember bamuProjectMember : projectMemberList) {
                    projectIdList.add(bamuProjectMember.getProjectId());
                }
            }else {
                // 默认返回一个项目id，表示没有项目，防止判断为空查询出所有项目
                projectIdList.add("-1");
            }
        }
        userVO.setProjectIds(projectIdList);
        return userVO;
    }

}
